package com.apes.fn.scm.appScan;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.server.productReceive.ProductReceive;
import com.apes.fn.server.productReceive.ProductReceiveItem;
import com.apes.fn.server.productReceive.ProductReceiveItemRepository;
import com.apes.fn.server.productReceive.ProductReceiveRepository;
import com.apes.fn.server.productReturn.ProductReturn;
import com.apes.fn.server.productReturn.ProductReturnItem;
import com.apes.fn.server.servicePlan.model.ServicePlan;
import com.apes.fn.server.servicePlan.repository.ServicePlanRepository;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 配件归还
 */
@Component
public class ProductReturnTemplate extends SimpleTemplate {

    @Autowired
    private ProductReceiveRepository productReceiveRepository;
    @Autowired
    private ProductReceiveItemRepository productReceiveItemRepository;
    @Autowired
    private ServicePlanRepository servicePlanRepository;

    @Override

    public String[] identifys() {
        return new String[]{"GH0"};
    }

    @Override
    public JSONArray getOrderLists(SimpleRequest request, String origin) {
        JSONObject json = request.getJO();
        String localPermitId = json.getString("localPermitId");

        //查询单号
        if (origin == null) {
            return productReceiveRepository.findAllByLocalPermitId(localPermitId).stream()
                    .map(this::getOrders)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toCollection(JSONArray::new));
        } else if (localPermitId != null) {
            return productReceiveItemRepository.findAllByLocalPermitIdAndId(localPermitId, origin).stream()
                    .map(this::getOrderItemJO)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toCollection(JSONArray::new));
        }
        return null;
    }

    private JSONObject getOrders(ProductReceive productReceive){
        // 检查是否全部归还
        int size = productReceive.getProductReceiveItems().size();
        long returnedSize = productReceive.getProductReceiveItems().stream().filter( productReceiveItem -> productReceiveItem.getQtyNotReturn() == 0 ).count();
        if (size == returnedSize) return null;

        JSONObject result = new JSONObject();
        result.put("LYDH", productReceive.getId());
        result.put("DSB", productReceive.getId());
        if (productReceive.getSource() != null) {
            ServicePlan plan = servicePlanRepository.findOne(productReceive.getSource());
            if (plan.getFnCustomerExpand() != null) {
                result.put("CPHM", plan.getFnCustomerExpand().getCarLicense());
                result.put("DSB", result.get("LYDH") + "-" + result.get("CPHM"));
            }
        }
        return result;
    }

    private JSONObject getOrderItemJO(ProductReceiveItem productReceiveItem) {
        if (productReceiveItem.getQtyReceive() - productReceiveItem.getQtyReturned() == 0) return null;
        JSONObject result = new JSONObject();
        result.put("LYDH", productReceiveItem.getId());
        result.put("LYDXH", productReceiveItem.getId());

        result.put("SMJS", 0);
        result.put("LYSL", productReceiveItem.getQtyReceive());
        result.put("LYJS", productReceiveItem.getQtyReceive());
        result.put("YGHJS", productReceiveItem.getQtyReturned());
        result.put("YGHSL", productReceiveItem.getQtyReturned());
        result.put("DJSL", productReceiveItem.getQtyNotReturn());
        result.put("SPMC", productReceiveItem.getProduct().getName());
        result.put("SPID", productReceiveItem.getProduct().getId());
        result.put("HSBL", productReceiveItem.getProduct().getUom().getFactor());
        result.put("JLDW", productReceiveItem.getUom().getName());
        result.put("GSID", productReceiveItem.getProductReceive().getCompany().getId());
        return result;
    }

    @Override
    public void submit(SimpleRequest request) {
        ProductReturn productReturn = new ProductReturn();
        ProductReceive productReceive = productReceiveRepository.findOne((String) request.get("LYDH"));
        productReturn.setLocation(productReceive.getLocation());
        productReturn.setScanSign(true); //设置扫码标记
        productReturn.setState("create");
        productReturn.setRemark("扫码端归还");
        productReturn.setProductReturnItems(((JSONArray) request.get("WAR_TMCRKDMX")).stream().map(
                item -> {
                    JSONObject returnItem = (JSONObject) item;
                    ProductReturnItem productReturnItem = new ProductReturnItem();
                    productReturnItem.setProduct(getProduct(returnItem.getString("SPID")));
                    productReturnItem.setUom(productReturnItem.getProduct().getUom());
                    productReturnItem.setCompany(SpringManager.getBean(PartyRoleRepository.class).findOne((returnItem.getString("GSID"))));
                    productReturn.setCompany(productReturnItem.getCompany());
                    productReturnItem.setQtyReturn(returnItem.getDouble("SMJS") * returnItem.getDouble("HSBL"));
                    productReturnItem.setProductReceiveItem(productReceiveItemRepository.findOne(returnItem.getString("LYDH")));
                    productReturnItem.setRemark("扫码端归还");
                    return productReturnItem;
                }
        ).collect(Collectors.toList()));
        ProductReturn aReturn = invoke("stock.productReturn.create", MapUtil.mapped(productReturn));
        invoke("stock.productReturn.approve", MapUtil.mapped(aReturn));
    }
}
